<!--
 * @Author: RAY_HUI 1541917867@qq.com
 * @Date: 2025-07-08 16:15:47
 * @LastEditors: RAY_HUI 1541917867@qq.com
 * @LastEditTime: 2025-10-10 19:00:43
 * @FilePath: \website-reconstruction---vue\src\components\sections\product\ProductList.vue
 * @Description: 
 * 
 * Copyright (c) 2025 by ${git_name_email}, All Rights Reserved. 
-->
<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import ProductItem from './ProductItem.vue'
import { getProdutByLangAndType } from '@/api/xyybackend/getVoList.js'
import { useLangStore } from '@/stores/langStore'
import { storeToRefs } from 'pinia'
const { currentLang, brandId, parentId, productTypeId } = storeToRefs(
  useLangStore()
)
onMounted(async () => {
  const res = await getProdutByLangAndType({
    lang: 'en',
    productType: productTypeId.value,
    brandId: brandId.value,
  })
  products.value = res.rows
})
// 🔥 3. 监听 productTypeId 变化，自动请求
watch(
  () => [productTypeId.value, brandId.value, parentId.value],
  async ([newType, newBrand, newParent]) => {
    if (!newType && !newBrand && !newParent) return

    try {
      const res = await getProdutByLangAndType({
        lang: currentLang.value || 'en',
        productType: newType,
        brandId: newBrand,
      })
      products.value = res.rows
    } catch (err) {
      console.error('获取产品失败:', err)
      products.value = []
    }
  },
  { immediate: true } // ✅ 立即执行一次，相当于 onMounted
)
// 🔹 计算属性：根据 currentLang 返回正确的 title
const displayedProducts = computed(() => {
  const start = (currentPage.value - 1) * productsPerPage
  const end = start + productsPerPage
  return products.value
    .map((item) => {
      // ✅ 核心逻辑：根据语言决定显示哪个标题
      const title =
        currentLang.value === 'en'
          ? item.nameTranslate || item.name // 英文优先用翻译，没有就用中文兜底
          : item.name

      return {
        id: item.id,
        title, // 动态切换
        image: item.imageUrl,
        modelNumber: item.modelNumber,
        rating: item.rating,
      }
    })
    .slice(start, end)
})
const displayMessage = computed(() => {
  const count = displayedProducts.value.length
  const baseText =
    currentLang.value === 'en'
      ? `Displaying ${count} products`
      : `正在展示 ${count} 个产品`

  // 可以更智能一点：单复数
  const text =
    currentLang.value === 'en'
      ? count === 1
        ? `Displaying 1 product`
        : `Displaying ${count} products`
      : `正在展示 ${count} 个产品`

  return text
})

// 示例数据
const products = ref([])

// 当前页码
const currentPage = ref(1)

// 每页显示的产品数量
const productsPerPage = 8
// 计算总页数
const totalPages = computed(() =>
  Math.ceil(products.value.length / productsPerPage)
)

// 计算当前页显示的产品

// 切换到下一页
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
  }
}

// 切换到上一页
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
  }
}

// 跳转到指定页
const goToPage = (page) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}
// 排序选项
const sortOption = ref('asc')
// 应用排序
const applySort = () => {
  if (sortOption.value === 'asc') {
    products.value.sort((a, b) => a.name.localeCompare(b.name))
  } else {
    products.value.sort((a, b) => b.name.localeCompare(a.name))
  }
}
</script>

<template>
  <section class="section-padding bg-light-white">
    <div class="container">
      <div class="row">
        <div class="col-12">
          <div class="listing-top-heading mb-xl-20">
            <h6 class="no-margin text-custom-black">{{ displayMessage }}</h6>
            <div class="sort-by">
              <span class="text-custom-black fs-14 fw-600">Sort by</span>
              <select
                class="form-control form-control-custom custom-select"
                v-model="sortOption"
                @change="applySort"
              >
                <option value="asc">A to Z</option>
                <option value="desc">Z to A</option>
              </select>
            </div>
          </div>
        </div>

        <!-- 产品列表 -->
        <ProductItem
          v-for="product in displayedProducts"
          :key="product.id"
          v-bind="product"
        />
      </div>
    </div>

    <!-- 分页控件 -->
    <div class="row">
      <div class="col-12">
        <nav>
          <ul class="pagination justify-content-center">
            <li class="page-item" :class="{ disabled: currentPage === 1 }">
              <a class="page-link" href="#" @click.prevent="prevPage"
                >Previous</a
              >
            </li>
            <li
              v-for="page in totalPages"
              :key="page"
              class="page-item"
              :class="{ active: page === currentPage }"
            >
              <a class="page-link" href="#" @click.prevent="goToPage(page)">{{
                page
              }}</a>
            </li>
            <li
              class="page-item"
              :class="{ disabled: currentPage === totalPages }"
            >
              <a class="page-link" href="#" @click.prevent="nextPage">Next</a>
            </li>
          </ul>
        </nav>
      </div>
    </div>
  </section>
</template>
